package com.cjz.tool.qr.utils;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import com.cjz.tool.qr.config.Setting;
import com.cjz.tool.qr.pojo.ParseResult;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import craky.util.SwingResourceManager;

public class Util {

	public static BufferedImage captureScreen() {
		try {
			Robot robot = new Robot();
			return robot.createScreenCapture(new Rectangle(Setting.screenSize));

		} catch (AWTException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static ParseResult parseImage(BufferedImage image) {
		Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
		hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

		LuminanceSource source = new BufferedImageLuminanceSource(image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

		QRCodeReader reader = new QRCodeReader();
		try {
			Result res = reader.decode(bitmap, hints);
			String resStr = res.getText();
			return new ParseResult(resStr != null && resStr.length() > 0, resStr);
		} catch (NotFoundException e) {
			e.printStackTrace();
			return new ParseResult(false, "没有找到QR码!");
		} catch (ChecksumException e) {
			e.printStackTrace();
			return new ParseResult(false, "校验和错误!");
		} catch (FormatException e) {
			e.printStackTrace();
			return new ParseResult(false, "格式错误!");
		}
	}

	public static void copyText2Clipboard(String writeMe) {
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable tText = new StringSelection(writeMe);
		clip.setContents(tText, null);
	}
}